package org.apache.database.helper;

import org.apache.database.enums.InsertActionEnum;
import org.apache.database.utils.AnnotationUtil;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class InsertHelper extends BaseHelper {

    public int insert(Object o) {
        String tabName = getTabName(o.getClass());

        List<String> fieldsNames = AnnotationUtil.getFieldsNames(o.getClass());

        List<Serializable> fieldValue = new ArrayList<>();

        Field[] declaredFields = o.getClass().getDeclaredFields();
        try {
            for (int i = 0; i < fieldsNames.size(); i++) {
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    if (AnnotationUtil.getColumnName(declaredField).equals(fieldsNames.get(i))) {

                        fieldValue.add((Serializable) declaredField.get(o));
                    }

                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        String insert = InsertActionEnum.BASE.init().withTableName(tabName).insert(fieldsNames, fieldValue);

        return getSqlExecute().execute(insert);
    }
}
